import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, Divider, Tag, message, Input,Card,Table,Form,Select, InputNumber,Radio,Col,Collapse,Row,Empty,DatePicker } from 'antd';
import React, { useState,useEffect } from 'react';
import { connect,history } from 'umi';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { saveMemberSigned,saveBookingCourse,cancelSign } from './service';
import styles from './style.less'
import {HasPermission} from '@/components/AuthComponent/HasPermission';
import {HasNoPermission} from '@/components/AuthComponent/HasNoPermission';
import db from '@/utils/localstorage';
import moment from 'moment'
import Resevation from './save'
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);
const AuthNoButton = HasNoPermission(Button);

const FormItem = Form.Item;
const { TextArea } = Input;
const { Panel } = Collapse;

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 5,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 18,
    },
    md: {
      span: 18,
    },
  },
};
const submitFormLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 18,
      offset: 5,
    },
  },
};



const ResevationList = props => {
  const { submitting,dispatch,memberBookInfoList,membersList,member,membersCardList,classTableInfoList,coachList,shopList,timeList,leftSiteList} = props;
  const [form] = Form.useForm();
  const [sorter, setSorter] = useState('');
  const [formValues, setFormValues] = useState({});
  const [visible, setVisible] = useState(false);
  const [venueId, setVenueId] = useState("");
  const [venueName, setVenueName] = useState("");
  const [classId, setClassId] = useState("");
  const [type, setType] = useState("");
  const [classIdSign, setClassIdSign] = useState("");
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cubeReservation/classTableInfoList',
        payload: {
          type:1,
          startDate:moment().format('YYYY-MM-DD'),
        },
      })
      dispatch({
        type: 'cubeReservation/fetchCoach',
        payload: {
          empType:2,
        },
      })
     }
   }, []);
   const columns = [
    {
      title: '姓名',
      dataIndex: 'memberName',
      key: 'memberName',
      render: text => <a>{text}</a>,
    },
    {
      title: '预约时间',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (text,record) => <span>{record.startTime}~{record.endTime}</span>,
    },
    {
      title: '电话',
      dataIndex: 'memberPhone',
      key: 'memberPhone',
    },
    {
      title: '会员卡',
      dataIndex: 'cardName',
      key: 'cardName',
    },
    {
      title: '场地',
      dataIndex: 'siteName',
      key: 'siteName',
    },
    {
      title: '人数',
      dataIndex: 'bookingNum',
      key: 'bookingNum',
    },
    {
      title: '课程价格',
      key: 'sellPrice',
      dataIndex: 'sellPrice',
    },
    {
      title: '备注',
      key: 'zb',
      dataIndex: 'zb',
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      render: (text, record) => {
       let bookingCourseType = db.get("dictTypeList")["booking_course_type"]
       let _status = bookingCourseType.filter((item)=>item.value == text )
       if(_status&&_status.length>0){
        return _status[0].label
       }
      }
    },
    {
      title: '预约时间',
      key: 'appointmentTime',
      dataIndex: 'appointmentTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <>
       {
         (record.status =='1'||record.status =='2')? <AuthButton auth={[`sign:reservation:sign`]} type="link"  onClick={() => sign(record)}>签到</AuthButton>:""
       }
       {
         (record.status =='1'||record.status =='2')?<AuthDivider auth={['sign:reservation:sign','sign:reservation:reservation:no']} type="vertical"></AuthDivider>:""
       }
        {
          (record.status =='1'||record.status =='2'||record.status =='6')&&<AuthButton auth={[`sign:reservation:reservation:no`]} type="link"  onClick={() => _cancelSign(record)}>取消预约</AuthButton>
        }
        </>
      ),
    },
  ];

  /**
   * 取消预约
   * @param {*} record 
   */
 const _cancelSign = async record  =>{
  const hide = message.loading('正在取消预约');
  let params={
    id:record.bookingCourseId,
    status:record.status
  }
  try {
    let result = await cancelSign({ ...params });
    hide();
    if(result.code==0){
      message.success('取消成功');
      dispatch({
        type: 'cubeReservation/queryMemberBookingCourseInfoByClassId',
        payload: {
          classId:record.classId
        },
      });
      return true;
    }else{
      message.success(result.message);
      return false;
    }
  } catch (error) {
    hide();
    message.error('取消失败，请重试！');
    return false;
  }
 }

  /**
   * 签到
   */
  const sign = async record =>{
    const hide = message.loading('正在签到');
    let params={}
    params.cardId=record.cardId
    params.cost=record.bookingNum
    params.memberId=record.memberId
    params.bookingCourseId=[record.bookingCourseId]
    params.zb='预约点击签到'
    try {
      let result = await saveMemberSigned({ ...params });
      hide();
      if(result.code==0){
        message.success('签到成功');
        dispatch({
          type: 'cubeReservation/queryMemberBookingCourseInfoByClassId',
          payload: {
            classId:classIdSign
          },
        });
        return true;
      }else{
        message.success(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('签到失败，请重试！');
      return false;
    }
  }
  const showModal = () => {
    setVisible(true)
  };

  const hideModal = () => {
    setVisible(false)
    setVenueId("")
    setVenueName("")
    setClassId("")
    setType("")
    setClassIdSign("")
    dispatch({
      type: 'cubeReservation/common',
      payload: {
        membersList:[],
        member:null
      },
    });
  };

   //去预约
  const gotoYuyue = (venueId,classId,type,venueName) =>{
    setVenueId(venueId)
    setClassId(classId)
    setVenueName(venueName)
    setClassIdSign(classId)
    setType(type)
    if(type=='3'){
      dispatch({
        type: 'cubeReservation/fetchTimeList',
        payload: {
          classId:classId
        },
      })
      dispatch({
        type: 'cubeReservation/querySiteInfoListByVenueIdNotPage',
        payload: {
          id:venueId
        },
      })
      showModal()
    }else{
      showModal()
    }
  }

  //添加预约
  const onFinish = async (values,callback) =>{
    const hide = message.loading('正在添加');
    values.classId=classId
    values.memberId=member.id
    try {
      let result = await saveBookingCourse({ ...values });
      hide();
      if(result.code==0){
        callback&&callback()
        hideModal();
        message.success('添加成功');
        if(!formValues.startDate){
          formValues.startDate=moment().format('YYYY-MM-DD')
        }
        dispatch({
          type: 'cubeReservation/classTableInfoList',
          payload: {
            type:1,
            ...formValues
          },
        })
        dispatch({
          type: 'cubeReservation/queryMemberBookingCourseInfoByClassId',
          payload: {
            classId:classId
          },
        });
        return true;
      }else{
        message.success(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('添加失败，请重试！');
      return false;
    }
  }

   //会员查询
  const handleSearch = (value) =>{
    if(value){
      let timeout;
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      function fake() {
        dispatch({
          type: 'cubeReservation/fetchMembersList',
          payload: {
            text:value
          },
        })
      }
      timeout = setTimeout(fake, 500);
    }else{
      dispatch({
        type: 'cubeReservation/common',
        payload: {
          membersList:[]
        },
      });
    }
  }

  //选择会员
  const handleSelect = value =>{
      //检索会员基本信息
      let member = membersList.filter((item) => {
        return item.id == value;
      });
      if(!!member&&member.length>0){
        dispatch({
          type: 'cubeReservation/common',
          payload: {
            member:member[0]
          },
        });
      }else{
        dispatch({
          type: 'cubeReservation/common',
          payload: {
            member:null
          },
        });
      }
      dispatch({
        type: 'cubeReservation/getMemberCard',
        payload: {
          memberId:value,
          venueId:venueId
        },
      });
  }

  const courseChange = (id) =>{
    setClassIdSign(id)
    dispatch({
      type: 'cubeReservation/queryMemberBookingCourseInfoByClassId',
      payload: {
        classId:id
      },
    });
  }
  /**
   * 查询
   * @param {*} values 
   */
  const onSearch = async() =>{
    const values = await form.validateFields();
    if(values.startDate){
      values.startDate=moment(values.startDate).format('YYYY-MM-DD')
    }
    setFormValues(values);
    dispatch({
      type: 'cubeReservation/classTableInfoList',
      payload: {
        type:1,
        ...values
      },
    })
  }
  /**
   * 重置
   */
  const handleReset = () =>{
    form.resetFields()
    setFormValues({});
    dispatch({
      type: 'cubeReservation/classTableInfoList',
      payload: {
        type:1,
        startDate:moment().format('YYYY-MM-DD'),
      },
    })
  }

  /**
   * 跳转预约记录
   * @param {*} courseId 
   */
  const goDetail = (id) =>{
    history.push(`/sign/reservation/detail/${id}`);
  } 

   /**
   * 跳转教练详情
   * @param {*} record 
   */
  const go2UserDetail = (record) =>{
    history.push(`/employee/list/detail/${record.coachId}`);
  }
  const options = membersList.map(d => <Option key={d.id}>{d.name}({d.phone})</Option>);
  console.log('leftSiteList???',leftSiteList)
  const saveProps={
    visible,
    hideModal,
    onFinish,
    handleSearch,
    handleSelect,
    options,
    member,
    membersCardList,
    submitting,
    type,
    timeList,
    siteList: leftSiteList,
    venueName,
    venueId,
    classId,
    dispatch
  }
 return (
    <PageHeaderWrapper>
      <Card style={{marginBottom:24}}>
              <Form  form={form} name="basic" layout="inline" initialValues={{startDate:moment()}}>
              <Row gutter={{ md: 6, lg: 24, xl: 48 }} style={{width:'100%',marginBottom:24}}>
                <Col md={6} sm={24}>
                  <FormItem label="教练" name="coachId">
                    <Select placeholder="请选择" style={{ width: '100%' }} allowClear>
                      {
                            coachList&&coachList.map((item,index)=><Select.Option value={item.userId} key={index}>{item.name}</Select.Option>)
                      }
                    </Select>
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <FormItem label="课程类型" name="classType">
                    <Select placeholder="请选择" style={{ width: '100%' }} allowClear>
                      {
                            db.get("dictTypeList")&&db.get("dictTypeList")["course_type"].map((item,index)=><Select.Option value={item.value} key={index}>{item.label}</Select.Option>)
                        }
                    </Select>
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <FormItem label="日期" name="startDate">
                      <DatePicker style={{width:'100%'}}/>
                  </FormItem>
                </Col>
              <Col md={6} sm={24}>
                  <span className={styles.submitButtons}>
                    <Button type="primary" onClick={onSearch}>查询</Button>
                    <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
                  </span>
                </Col>
              </Row>
            </Form>
        </Card>
        <Card title="预约课程">
            {
              classTableInfoList&&classTableInfoList.length>0? <Collapse onChange={courseChange} accordion>
              {
                 classTableInfoList.map((item,index)=><Panel key={item.id} header={
                <span className={styles.title}>
                  <span>
                    <Tag color="#f50">{item.type=='1'?'团课':item.type=='2'?'小班课':item.type=='3'?'私教课':''}</Tag>
                    <span>{item.openingTimeHour}:{item.openingTime}~{item.endTime}</span>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <a onClick={()=>goDetail(item.id)}>{item.courseName}</a>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <a onClick={()=>go2UserDetail(item)}>{item.coachName}</a>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <span>{item.venueName}</span>
                  </span>
                  <span className={styles.leftWrap}>
                    <span>剩余可预约时间段：</span>
                    {
                      item?.usableTimeVOS?.filter(item=>item.status ==='1')?.map((item,index)=><span key={index}>{item.startTime}</span>)
                    }
                  </span>
                  </span>
                } extra={
                <><span className={styles.extra}><span className={styles.exist}>{item.bookingNum||0}</span>/{item.maximumAttendance}</span>&nbsp;&nbsp;&nbsp;&nbsp;{<AuthButton auth={[`sign:reservation:reservation`]} type="primary" onClick={(e)=>{
                  e.stopPropagation();
                  gotoYuyue(item.venueId,item.id,item.type,item.venueName)
                }} icon={<PlusOutlined />}>预约</AuthButton>}</>
                }>
                <Table columns={columns} dataSource={memberBookInfoList} pagination={false}/>
              </Panel>)
              }
            </Collapse>:<Empty/>
            }
        </Card>
        <Resevation {...saveProps}/>
    </PageHeaderWrapper>
  );
};

export default connect(({ loading, cubeReservation }) => ({
  submitting: loading.effects['cubeReservation/add'],
  membersList:cubeReservation.membersList,
  member:cubeReservation.member,
  membersCardList:cubeReservation.membersCardList,
  classTableInfoList:cubeReservation.classTableInfoList,
  memberBookInfoList:cubeReservation.memberBookInfoList,
  shopList:cubeReservation.shopList,
  coachList:cubeReservation.coachList,
  timeList:cubeReservation.timeList,
  siteList:cubeReservation.siteList,
  leftSiteList: cubeReservation.leftSiteList
}))(ResevationList);